<template>
  <div id="echarts-container" style="width: 100%; height: 400px;"></div>
</template>

<script setup>
import {onMounted, ref} from "vue";
import * as echarts from "echarts";
import axios from "axios"; // 导入 axios

const pieData = ref([]); // 用于存储车位状态数据

// 初始化 ECharts
const drawChart = () => {
  const chartDom = document.getElementById("echarts-container");
  const myChart = echarts.init(chartDom);

  const option = {
    title: {
      text: "车位状态分布",
      left: "center",
    },
    tooltip: {
      trigger: "item",
    },
    legend: {
      orient: "vertical",
      left: "left",
    },
    series: [
      {
        name: "车位状态",
        type: "pie",
        radius: "50%",
        data: pieData.value,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: "rgba(0, 0, 0, 0.5)",
          },
        },
      },
    ],
  };

  myChart.setOption(option);
};

// 获取车位状态分布数据
const fetchStatusDistribution = async () => {
  try {
    let pageNum = 1;
    let pageSize = 100; // 设置合适的分页大小
    let statusCount = {"闲置": 0, "自用": 0, "租赁": 0, "借出": 0}; // 存储每个状态的数量

    // 分页获取车位数据并统计每个状态的数量
    while (true) {
      const response = await axios.get("http://localhost:8080/vehiclePosition/list", {
        headers: {
          Authorization: localStorage.getItem("token"),
        },
        params: {pageNum, pageSize}
      });
      const vehiclePositions = response.data.records;
      console.log(vehiclePositions);
      // 遍历当前页的数据，统计车位状态数量
      vehiclePositions.forEach((vehiclePosition) => {
        if (vehiclePosition.status === "1") {
          statusCount["闲置"] += 1;
        } else if (vehiclePosition.status === "2") {
          statusCount["自用"] += 1;
        } else if (vehiclePosition.status === "3") {
          statusCount["租赁"] += 1;
        } else if (vehiclePosition.status === "4") {
          statusCount["借出"] += 1;
        }
      });

      // 如果当前页数据不足分页大小，说明已经是最后一页
      if (vehiclePositions.length < pageSize) {
        break;
      }
      // 如果还有更多数据，继续请求下一页
      pageNum++;
    }

    // 将统计结果转为 ECharts 数据格式
    pieData.value = [
      {value: statusCount["闲置"], name: "闲置"},
      {value: statusCount["自用"], name: "自用"},
      {value: statusCount["租赁"], name: "租赁"},
      {value: statusCount["借出"], name: "借出"}
    ];
    drawChart(); // 绘制图表
  } catch (error) {
    console.error("获取车位数据失败:", error);
  }
};

// 页面加载时获取数据
onMounted(() => {
  fetchStatusDistribution();
});
</script>

<style scoped>
#echarts-container {
  background-color: white;
  padding: 20px;
  margin: 20px auto;
  border-radius: 8px;
}
</style>
